
#include "LCD03.h"
#include "RP6I2CmasterTWI.h"
#include <avr/pgmspace.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

char lcd_tmp_buffer[21];
uint8_t lcdInitialized=false;

uint8_t LCD03_isInitialized(void)
{
	return lcdInitialized;	
}

void LCD03_writeCommand(uint8_t cmd)
{
	while(I2CTWI_isBusy()){
	}
	I2CTWI_transmit2Bytes(LCD03_ADDRESS,0,cmd);
}

void LCD03_clear(void)
{
	LCD03_writeCommand(LCD03_CLEAR_SCREEN);
}

void LCD03_writeChar(uint8_t ch)
{
	if(ch >= 32 && ch <= 255){
		LCD03_writeCommand(ch);
	}
}

void LCD03_writeNString_P(const char *pstring)
{
    uint8_t c;
    for (;(c = pgm_read_byte_near(pstring++));LCD03_writeChar(c));
}

void LCD03_writeString(char *string)
{
	while(*string){
		LCD03_writeChar(*string++);
	}		
}

void LCD03_writeStringLength(char *string, uint8_t length, uint8_t offset)
{
	for(string = &string[offset]; *string && length; length--){
		LCD03_writeChar(*string++);
	}		
}

void LCD03_writeInteger(int16_t number, uint8_t base)
{
	itoa(number, &lcd_tmp_buffer[0], base);
	LCD03_writeString(&lcd_tmp_buffer[0]);
}

void LCD03_writeIntegerLength(int16_t number, uint8_t base, uint8_t length)
{
	char buffer[21];
	itoa(number, &buffer[0], base);
	int8_t cnt = length - strlen(buffer);
	if(cnt > 0) {
		for(; cnt > 0; cnt--, LCD03_writeChar('0'));
		LCD03_writeString(&buffer[0]);
	}
	else 
		LCD03_writeStringLength(&buffer[0],length,-cnt);
}

void _LCD03_showScreen(const char *line1, const char *line2)
{
	LCD03_clear();
	LCD03_writeNString_P(line1);
	LCD03_setCursorPos(1, 1);
	LCD03_writeNString_P(line2);
}

void _LCD03_showScreen3(const char *line1, const char *line2, const char *line3)
{
	LCD03_clear();
	LCD03_writeNString_P(line1);
	LCD03_setCursorPos(2, 1);
	LCD03_writeNString_P(line2);
	LCD03_setCursorPos(3, 1);
	LCD03_writeNString_P(line3);
}

void LCD03_writeFloat(float f){
	char buffer[17];
	dtostrf(f,16,2,buffer);
	char *string = &buffer[0];
	while(*string){
		if(*string!=' '){
			LCD03_writeChar(*string++);
		}else{
			++(*string);
		}
	}	
}


void _LCD03_showScreen4(const char *line1, const char *line2, const char *line3, const char *line4)
{
	LCD03_clear();
	LCD03_writeNString_P(line1);
	LCD03_setCursorPos(2, 1);
	LCD03_writeNString_P(line2);
	LCD03_setCursorPos(3, 1);
	LCD03_writeNString_P(line3);
	LCD03_setCursorPos(4, 1);
	LCD03_writeNString_P(line4);
}

void LCD03_setCursorPos(uint8_t line, uint8_t pos)
{
	I2CTWI_transmit4Bytes(LCD03_ADDRESS,0,LCD03_SET_CURSOR_LINE_COL, line, pos);
}

void LCD03_clearPos(uint8_t line, uint8_t pos, uint8_t length)
{
	LCD03_setCursorPos(line,pos);
	while(length--){
		LCD03_writeChar(' ');
	}		
}
